package com.blogzhxs.model;

import java.io.*;

/**
 * Created by 醉花阴柳 on 2016/12/9.
 */
public class BOMFile {
    private FileInputStream fileInputStream;
    private String fileName;
    private String outFileName;
    //byte表示8为即一个字节
    private static final byte[] bom = {0xef-0xff-1,0xbb-0xff-1,0xbf-0xff-1};
    private byte[] buf = new byte[3];

    public BOMFile(File file){
        fileName = file.getAbsolutePath();
        outFileName = fileName+".new";
        try {
            fileInputStream = new FileInputStream(fileName);
            readBOM(fileInputStream);
        }catch (Exception e){
            e.printStackTrace();
        }
//        for(byte b:buf){
//            System.out.print(Integer.toHexString(b&0xFF)+" ");
//        }
//        System.out.println();
//        System.out.println(existBOM());
    }

    //判断是否存在BOM
    public boolean existBOM(){
        for(int i = 0; i < bom.length; i++){
            if(bom[i] != buf[i]){
                return false;
            }
        }
        return true;
    }

    //若存在BOM则移除
    public boolean removeBOM(){
        FileOutputStream fileOutputStream = null;
        if(fileInputStream == null)
            return false;
        if(existBOM()){
            try {
                fileOutputStream = new FileOutputStream(outFileName);
                byte[] tmp = new byte[1024];
                int len;
                while((len = fileInputStream.read(tmp)) != -1){
                    fileOutputStream.write(tmp,0,len);
                }
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }finally {
                try {
                    fileInputStream.close();
                    fileOutputStream.close();
                } catch (Exception e) {
                    System.out.println("关闭输出输入流异常!");
                    return false;
                }
            }
        }
        delAndRenameFileName();
        return true;
    }

    //读取开头的三个字节
    private void readBOM(FileInputStream fis){
        try {
            fis.read(buf);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void delAndRenameFileName(){
        File oldFile = new File(fileName);
        File newFile = new File(outFileName);
        oldFile.delete();
        newFile.renameTo(oldFile);
    }

}
